import React, { useCallback, useMemo, useRef } from 'react';
import '../macDock/macDock.less'

interface ItemData {
  color: string;
}

interface ItemProps {
  color: string;
  clientX: number;
}

interface ScaleCurveParams {
  curveCentreX: number;
  menuItemX: number;
}

const data: ItemData[] = [
  {color: '#ff4d4f'},
  {color: '#ff7a45'},
  {color: '#ffa940'},
  {color: '#ffc53d'},
  {color: '#ffec3d'},
  {color: '#bae637'},
  {color: '#73d13d'},
  {color: '#36cfc9'},
  {color: '#4096ff'},
  {color: '#597ef7'},
  {color: '#9254de'},
  {color: '#f759ab'},
];

const curveRange = 600; // 波形范围
const minScale = 1; // 最小的缩放比例
const maxScale = 1.8; // 最大的缩放比例

const Item: React.FC<ItemProps> = ({ color, clientX }) => {
  const ref = useRef<HTMLDivElement>(null);
  const scale = useMemo(() => {
    if (!ref.current) {
      return minScale;
    }
    const { left, width } = ref.current.getBoundingClientRect();
    return scaleCurve({
      curveCentreX: clientX,
      menuItemX: left + (width / 2),
    });
  }, [clientX]);

  return (
    <div
      ref={ref}
      className="item"
      style={{ 
        backgroundColor: color, 
        '--scale': scale 
      } as React.CSSProperties}
    />
  );
};

const scaleCurve = ({ curveCentreX, menuItemX }: ScaleCurveParams): number => {
  const beginX = curveCentreX - (curveRange / 2);
  const endX = curveCentreX + (curveRange / 2);

  if (menuItemX < beginX || menuItemX > endX) {
    return minScale;
  }

  const amplitude = maxScale - minScale;
  const angle = ((menuItemX - beginX) / curveRange) * Math.PI;

  return (Math.sin(angle) * amplitude) + minScale;
};

const MacDock: React.FC = () => {
  const [clientX, setClientX] = React.useState<number>(0);
  const wrapperRef = useRef<HTMLDivElement>(null);

  const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    if (wrapperRef.current) {
      wrapperRef.current.style.setProperty('--transition-duration', '0.08s');
      setClientX(e.clientX);
      setTimeout(() => {
        wrapperRef.current?.style.setProperty('--transition-duration', '0s');
      }, 100);
    }
  }, []);

  const handleMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
    console.log(11)
    setClientX(e.clientX);
  }, []);

  const handleMouseLeave = useCallback(() => {
    if (wrapperRef.current) {
      wrapperRef.current.style.setProperty('--transition-duration', '0.08s');
      setClientX(0);
      setTimeout(() => {
        wrapperRef.current?.style.setProperty('--transition-duration', '0s');
      }, 100);
    }
  }, []);

  return (
    <div className="main">
      <div className="wrapper"
        ref={wrapperRef}
        onMouseEnter={handleMouseEnter}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}>
        {data.map((v, index) => (
          <Item key={index} color={v.color} clientX={clientX} />
        ))}
      </div>
    </div>
  );
};

export default MacDock;
